package com.ruoyi.gateway.config;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.gateway.domain.dto.SystemStats;
import com.ruoyi.gateway.service.GatewayMonitorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@Component
public class MonitorWebSocketHandler extends TextWebSocketHandler {

    private static final Set<WebSocketSession> sessions = Collections.synchronizedSet(new HashSet<>());

    @Autowired
    private GatewayMonitorService monitorService;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        // 发送当前状态
        sendSystemStats(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
    }

    public void broadcastMessage(String message) {
        synchronized (sessions) {
            for (WebSocketSession session : sessions) {
                if (session.isOpen()) {
                    try {
                        session.sendMessage(new TextMessage(message));
                    } catch (Exception e) {
                        // 忽略发送失败的情况
                    }
                }
            }
        }
    }

    private void sendSystemStats(WebSocketSession session) throws Exception {
        SystemStats stats = monitorService.getSystemStats();
        String json = JSON.toJSONString(stats);
        session.sendMessage(new TextMessage("STATS:" + json));
    }
}
